package controller.Seller;

import com.alibaba.fastjson.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import pojo.Goods;
import pojo.Page;
import service.Seller.GoodsService;
import service.Seller.impl.GoodsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

@WebServlet(name = "doGoodsServlet",urlPatterns = "/doGoodsServlet")
public class doGoodsServlet extends HttpServlet {
    Page page= new Page();       //设置全局变量读取
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String action=request.getParameter("action");
        GoodsService gods= new GoodsServiceImpl();
        PrintWriter pw=response.getWriter();
        if(action.equals("select")){          //全部查询
            String goodsName=request.getParameter("goodsName");
            int smallName= Integer.parseInt(request.getParameter("smallName"));
            int sellerName=Integer.parseInt(request.getParameter("sellerName"));
            List<Goods> ListGoodes=gods.getFuzzyquery(goodsName,smallName,sellerName);
            StringBuffer sb=new StringBuffer("[");
            for (int i=0;i<ListGoodes.size();i++){
                sb.append("{\"id\":"+ListGoodes.get(i).getId()+",\"goodsName\":\""+ListGoodes.get(i).getGoodsName()+"\",\"goodsSmalId\":\""+ListGoodes.get(i).getGoodsSmalId()+"\",\"goodsMoney\":\""+ListGoodes.get(i).getGoodsMoney()+
                        "\",\"goodsNumber\":\""+ListGoodes.get(i).getGoodsNumber()+"\",\"goodsImage;\":\""+ListGoodes.get(i).getGoodsImage()+"\",\"goodsCarriage\":\""+ListGoodes.get(i).getGoodsCarriage()+"\",\"goodsType\":\""+ListGoodes.get(i).getGoodsType()+
                        "\",\"goodsSeId\":\""+ListGoodes.get(i).getGoodsSeId()+"\",\"goodsDiscId\":\""+ListGoodes.get(i).getGoodsDiscId() +"\"}");
                if(i!=ListGoodes.size()-1){
                    sb.append(",");
                }
            }
            sb.append("]");
            pw.write(sb.toString());
            pw.flush();
            pw.close();
        }
        else if(action.equals("fuzzy")){         //模糊查询
            String goodsName=request.getParameter("goodsName");
            int smallName= Integer.parseInt(request.getParameter("smallName"));
            int sellerName=Integer.parseInt(request.getParameter("sellerName"));
            List<Goods> ListGoodes=gods.getFuzzyquery(goodsName,smallName,sellerName);
            String str=JSON.toJSONStringWithDateFormat(ListGoodes,"yyyy-MM-dd");
            pw.write(str.toString());
            pw.flush();
            pw.close();
        }
        else if(action.equals("selectPage")){     //获得总页数的方法
            //获取到当前页数
            String str=request.getParameter("index");
            //获取到商家名称
            String sellerName=request.getParameter("sellerName");
            //获取小分类
            String smallName=request.getParameter("smallName");
            int cid=smallName==null?-1:Integer.parseInt(smallName);
            //设置页面显示的数据条数
            page.setRow(6);
            page.setCount(gods.getCount(cid,sellerName));
            page.setCountPages(gods.getCountPage(page.getCount(),page.getRow()));
            //设置当前显示的第一条数据
            page.setIndex(1);
            if(str!=null && str!=""){
                page.setIndex(Integer.parseInt(str));
                //当前页数不能大于最大页数
                if(page.getIndex()>page.getCountPages()){
                    page.setIndex(page.getCountPages());
                }else if(page.getIndex()<1){  //当前最小页不能小于1
                    page.setIndex(1);
                }
            }
            List<Goods> goods =gods.NewsfindAll(cid,sellerName,page.getIndex(),page.getRow());
            String  strPage= JSON.toJSONString(goods);
            pw.write(strPage);
            pw.flush();
            pw.close();
        }
        else if(action.equals("getPage")){         //获取页数
            String  strPage=JSON.toJSONStringWithDateFormat(page,"yyyy-MM-dd");
            pw.write(strPage);
            pw.flush();
            pw.close();
        }
        else  if(action.equals("goodsQueryById")){    //转发到数据显示页面
            response.sendRedirect("/Seller/goodsQuery.jsp");
        }
        else if(action.equals("addGoods")){          //添加商品
            Goods goods =new Goods();
            //接收增加的新闻信息，并调用后台方法，将新闻信息插入数据库
            String uploadFileName = "";
            String fieldName = "";
            //解析请求之前先判断请求类型是否为文件上传类型
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            //指定上传位置
            String uploadFilePath = request.getSession().getServletContext().getRealPath("GoodsImage/");
            File saveDir = new File(uploadFilePath);
            //如果目录不存在，就创建目录
            if(!saveDir.exists()){
                saveDir.mkdir();
            }
            if(isMultipart){
                //创建文件上传核心类
                FileItemFactory factory = new DiskFileItemFactory(); // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
                ServletFileUpload upload = new ServletFileUpload(factory); // 用以上工厂实例化上传组件
                try{
                    //处理表单请求
                    List<FileItem> items = upload.parseRequest(request);
                    Iterator<FileItem> iter = items.iterator();
                    while(iter.hasNext()){
                        FileItem item = (FileItem)iter.next();
                        if(item.isFormField()){// 如果是普通表单控件
                            fieldName = item.getFieldName();// 获得该字段名称
                            if(fieldName.equals("goodsName")){
                                goods.setGoodsName(item.getString("utf-8"));
                            }else if(fieldName.equals("goodsSmalId")){
                                goods.setGoodsSmalId(Integer.parseInt(item.getString("utf-8")));
                            }else if(fieldName.equals("goodsMoney")){
                                goods.setGoodsMoney(Double.parseDouble(item.getString("utf-8")));
                            }else if(fieldName.equals("goodsNumber")){
                                goods.setGoodsNumber(Long.parseLong(item.getString("utf-8")));
                            }else if(fieldName.equals("goodsCarriage")){
                                goods.setGoodsCarriage(Double.parseDouble(item.getString("utf-8")));
                            }else if(fieldName.equals("goodsType")){
                                goods.setGoodsType(Long.parseLong(item.getString("utf-8")));
                            } else if(fieldName.equals("goodsDiscId")){
                                goods.setGoodsDiscId(Integer.parseInt(item.getString("utf-8")));
                            }
                        }else{// 如果为文件域
                            String fileName = item.getName();// 获得文件名(全路径)
                            if(fileName != null && !fileName.equals("")){
                                File fullFile = new File(fileName);
                                File saveFile = new File(uploadFilePath,fullFile.getName());//将文件保存到指定的路径
                                item.write(saveFile);
                                uploadFileName = fullFile.getName();
                                goods.setGoodsImage(uploadFileName);
                            }
                        }
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
            System.out.println("上传成功之后的文件名：" + goods.getGoodsImage());
            //调用后台的方法，将新闻信息插入数据库中
            int n=gods.addGoods(goods);
            boolean flag=false;
            if(n>0) {
                flag=true;
                request.getRequestDispatcher("/Seller/goodsQuery.jsp?flag=true").forward(request, response);
            }else{
                request.getRequestDispatcher("/Seller/goodsAdd.jsp?flag=false").forward(request, response);
            }
            pw.flush();
            pw.close();
        }
        else if(action.equals("delete")){      ///删除
            String id =request.getParameter("id");
            int n=gods.deleteGoods(Integer.parseInt(id));
            boolean flag=false;
            if(n>0){
                flag=true;
            }
            String deleteJson="{\"flag\":\""+flag+"\"}";
            pw.write(deleteJson);
            pw.flush();
            pw.close();
        }else if(action.equals("update")){    //修改
            Goods goods =new Goods();
            //接收增加的新闻信息，并调用后台方法，将新闻信息插入数据库
            String uploadFileName = "";
            String fieldName = "";
            //解析请求之前先判断请求类型是否为文件上传类型
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            //指定上传位置
            String uploadFilePath = request.getSession().getServletContext().getRealPath("GoodsImage/");
            File saveDir = new File(uploadFilePath);
            //如果目录不存在，就创建目录
            if(!saveDir.exists()){
                saveDir.mkdir();
            }
            if(isMultipart){
                //创建文件上传核心类
                FileItemFactory factory = new DiskFileItemFactory(); // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
                ServletFileUpload upload = new ServletFileUpload(factory); // 用以上工厂实例化上传组件
                try{
                    //处理表单请求
                    List<FileItem> items = upload.parseRequest(request);
                    Iterator<FileItem> iter = items.iterator();
                    while(iter.hasNext()){
                        FileItem item = (FileItem)iter.next();
                        if(item.isFormField()){// 如果是普通表单控件
                            fieldName = item.getFieldName();// 获得该字段名称
                            if(fieldName.equals("goodsName")){
                                goods.setGoodsName(item.getString("utf-8"));
                            }else if(fieldName.equals("goodsSmalId")){
                                goods.setGoodsSmalId(Integer.parseInt(item.getString("utf-8")));
                            }else if(fieldName.equals("goodsMoney")){
                                goods.setGoodsMoney(Double.parseDouble(item.getString("utf-8")));
                            }else if(fieldName.equals("goodsNumber")){
                                goods.setGoodsNumber(Long.parseLong(item.getString("utf-8")));
                            }else if(fieldName.equals("goodsCarriage")){
                                goods.setGoodsCarriage(Double.parseDouble(item.getString("utf-8")));
                            }else if(fieldName.equals("goodsType")){
                                goods.setGoodsType(Long.parseLong(item.getString("utf-8")));
                            }else if(fieldName.equals("goodsSeId")){
                                goods.setGoodsSeId(Long.parseLong(item.getString("utf-8")));
                            } else if(fieldName.equals("goodsDiscId")) {
                                goods.setGoodsDiscId(Integer.parseInt(item.getString("utf-8")));
                            }else if(fieldName.equals("id")){
                                goods.setId(Long.parseLong(item.getString("utf-8")));
                            }
                        }else{// 如果为文件域
                            String fileName = item.getName();// 获得文件名(全路径)
                            if(fileName != null && !fileName.equals("")){
                                File fullFile = new File(fileName);
                                File saveFile = new File(uploadFilePath,fullFile.getName());//将文件保存到指定的路径
                                item.write(saveFile);
                                uploadFileName = fullFile.getName();
                                goods.setGoodsImage(uploadFileName);
                            }
                        }
                    }

                }catch(Exception e){
                    e.printStackTrace();
                }
            }
            System.out.println("上传成功之后的文件名：" + goods.getGoodsImage());
            //调用后台的方法，将新闻信息插入数据库中
            int n= gods.updataGoods(goods);
            if(n>0) {
                pw.print("<script>");
                pw.print("alert('修改成功！');");
                pw.print("location.href='/Seller/goodsQuery.jsp'");
                pw.print("</script>");
              //  request.getRequestDispatcher("/Seller/goodsQuery.jsp?flag=true").forward(request, response);
            }else{
                pw.print("<script>");
                pw.print("alert('修改失败！');");
                pw.print("location.href='/Seller/goodsUpdate.jsp'");
                pw.print("</script>");
            }
            pw.flush();
            pw.close();
        }else if(action.equals("getGoodsID")){              //获得商品id
            String GoodsID=request.getParameter("GoodsID");
            Goods goods=gods.getGoodsId(Integer.parseInt(GoodsID));
            String newsJson= JSON.toJSONStringWithDateFormat(goods,"yyyy-MM-dd");
            pw.write(newsJson);
            pw.flush();
            pw.close();
        }
        pw.flush();
        pw.close();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      doPost(request,response);
    }
}
